import type { ChatListType } from "@/types/chatlist"
import { deleteChatListApi, getMyChatListApi } from '@/api/chatlist'
import { defineStore } from "pinia"
import { computed, ref } from "vue"

export const useChatListStore = defineStore(
  'chatLsit',
  () => {
    // 存储消息页面的聊天列表
    const chatList = ref<ChatListType[]>([])

    // 计算存储私信消息未读数量总数
    const privateLetterUnreadCount = computed(() => {
      return chatList.value.reduce((sum, item) => sum + item.noReadCount, 0)
    })

    // 存储私信消息未读数量
    // const privateLetterUnreadCount = ref(0)
    // 存储评论和回复消息未读数量
    const commentAndReplyUnreadCount = ref(0)
    // 存储新增关注消息未读数量
    const newFollowUnreadCount = ref(0)

    // 获取聊天列表
    const getChatLists = async () => {
      // 调用接口获取数据
      try {
        const res = await getMyChatListApi()
        if (res.code === 0) {
          chatList.value = res.data
        } else {
          ElMessage.error(res.msg)
        }
      } catch (error) {
        console.error(error)
      }
    }

    // 删除聊天列表
    const deleteChatList = async (chatListId: string) => {
      try {
        const res = await deleteChatListApi(chatListId)
        if (res.code === 0) {
          ElMessage.success('删除成功')
          getChatLists()
        } else {
          ElMessage.error(res.msg)
        }
      } catch (error) {
        console.error(error)
      }
    }

    return {
      chatList,
      privateLetterUnreadCount,
      commentAndReplyUnreadCount,
      newFollowUnreadCount,
      getChatLists,
      deleteChatList,
    }
  },
)
